<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Request;

/**
 * 豆包AI流式对话接口
 */
class Doubaoai extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 豆包AI流式对话接口
     * GET/POST /api/doubaoai/index
     * 参数: question=你好&temperature=0.7&max_tokens=4000&stream_mode=char
     * stream_mode: char(逐字符) | word(逐词) | chunk(分块) | complete(完整)
     */
    public function index(Request $request)
    {
        // API密钥（需替换为实际的ARK_API_KEY）
        $apiKey = '46870f23-6d7f-4460-bb6d-4a20370d46ae';
        // 请求URL
        $url = 'https://ark.cn-beijing.volces.com/api/v3/chat/completions';

        // 请求参数
        $data = [
            'model' => 'doubao-1-5-pro-32k-250115',
            'messages' => [
                [
                    'role' => 'system',
                    'content' => 'You are a helpful assistant.'
                ],
                [
                    'role' => 'user',
                    'content' => 'hello'
                ]
            ],
            'stream' => false // 启用流式响应
        ];

        // 初始化curl
        $ch = curl_init();

        // 设置curl选项
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => false, // 不直接返回结果，通过回调处理
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                "Authorization: Bearer {$apiKey}"
            ],
            // 处理流式响应的回调函数
            CURLOPT_WRITEFUNCTION => function ($ch, $data) {
                // 过滤空数据
                if (trim($data) === '') {
                    return strlen($data);
                }
                // 按SSE协议格式解析（每行以"data:"开头）
                $lines = explode("\n", $data);
                foreach ($lines as $line) {
                    $line = trim($line);
                    if ($line === 'data: [DONE]') {
                        // 流式结束标记
                        echo "流式响应结束\n";
                        break;
                    }
                    if (strpos($line, 'data: ') === 0) {
                        // 提取并解析JSON数据
                        $jsonStr = substr($line, 6);
                        $response = json_decode($jsonStr, true);
                        if (json_last_error() === JSON_ERROR_NONE) {
                            // 输出模型生成的内容（assistant的回复）
                            $content = $response['choices'][0]['message']['content'] ?? '';
                            if (!empty($content)) {
                                echo $content;
                            }
                        }
                    }
                }
                return strlen($data);
            },
            // 添加以下两行禁用SSL验证（测试用）
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);

        // 执行请求
        $response = curl_exec($ch);

        // 检查错误
        if (curl_errno($ch)) {
            echo "curl错误: " . curl_error($ch) . "\n";
        }

        // 关闭curl
        curl_close($ch);
    }

    public function streamChat() {
        $url = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
        $apiKey = "46870f23-6d7f-4460-bb6d-4a20370d46ae"; // 替换为您的 API 密钥
    
        $data = [
            "messages" => [
                [
                    "content" => "天空为什么是蓝色的？",
                    "role" => "user"
                ]
            ],
            "model" => "doubao-1-5-pro-32k-250115",
            "stream" => true
        ];
    
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
    
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "Authorization: Bearer $apiKey"
            ],
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_WRITEFUNCTION => function ($ch, $chunk) {
                echo "data: " . $chunk . "\n\n";
                ob_flush();
                flush();
                return strlen($chunk);
            },
        ]);
    
        curl_exec($ch);
    
        if (curl_errno($ch)) {
            echo "event: error\n";
            echo "data: " . curl_error($ch) . "\n\n";
        }
    
        curl_close($ch);
    }
}
